<template>
  <Designer ref="ddesigner">
    <template v-slot:header>
      <div class="design-name">{{ state.name }}</div>
    </template>
    <template v-slot:actions-before>
      <el-button @click="handleSubmit" type='primary' size="mini">本地保存</el-button>
      <el-button v-if="isHasLocal && state.id" @click="handleUseOrigin" size="mini">使用原始数据</el-button>
      <el-button v-if="isHasLocal && state.id" @click="handleClearLocal" size="mini">清除本地数据</el-button>
      <el-button v-if="state.id" @click="handlePreview" type='primary' size="mini">预览</el-button>
    </template>
  </Designer>
</template>

<script>
import Designer from './designer.vue'
import { objecter, parser, dater, strer, storeLocal } from '@daelui/dogjs/dist/components.js'
import { Dialoger, FormGroup, FormInput, FormTextarea, Grid, GridColumn } from '@daelui/vdog/dist/components.js'
import { SeeIcon, DeleteIcon } from '@daelui/vdog/dist/icons.js'
import { zh as locale } from '@daelui/dogjs/dist/locale.js'
import { state, setter } from '@/service/stock/index'
import vrSer from '@/service/action/viewrelease.action'
import vcSer from '@/service/action/viewcomp.action'
import componentCollection from './components/components'

export default {
  components: {
    Designer,
    Dialoger,
    FormGroup, FormInput, FormTextarea,
    Grid, GridColumn,
    SeeIcon, DeleteIcon
  },

  data () {
    return {
      isEdit: false, // 是否是编辑模式
      // 表单数据
      state: {
        id: '',
        pid: '',
        name: '',
        meta: {},
        layout: '',
        description: '',
        status: 1,
        order: 1,
        updateTime: '',
        updateUser: '',
        createTime: '',
        createUser: ''
      },
      isHasLocal: false, // 是否有本地版本
      isShowRelease: false, // 是否显示发布框
      releaseName: '',
      releaseDesc: '', // 发布描述
      isShowReleaseList: false,
      releaseList: [] // 发布版本列表
    }
  },

  methods: {
    /**
     * @function 加载数据
    */
    loadItem (id) {
      vrSer.queryItemSaas({ vpid: id }).then(result => {
        let data = result.data || {}
        if (!data.id) {
          data  = {
            "name":"演练",
            "path":"drill",
            "code":"",
            "description":"",
            "mid":"",
            "status":1,
            "order":1,
            "updateUser":"",
            "createUser":"",
            "layout":"ddesign-layout-fill",
            "meta":"{\"name\":\"ddesign-layout-fill\",\"properts\":{},\"layout\":{\"columns\":[{\"id\":1,\"colWidth\":\"auto\"}],\"rows\":[{\"id\":1,\"rowHeight\":\"auto\"}],\"margin\":{\"top\":\"0px\",\"right\":\"0px\",\"bottom\":\"0px\",\"left\":\"0px\"},\"padding\":{\"top\":\"8px\",\"right\":\"8px\",\"bottom\":\"8px\",\"left\":\"8px\"},\"areas\":[],\"rowGap\":\"8px\",\"colGap\":\"8px\",\"contrast\":{\"isAble\":true,\"bgColor\":\"#ffffff\"}},\"events\":{},\"resource\":{\"files\":[]},\"theme\":{},\"childComponents\":[]}",
            "version":"0.0.0",
            "labels":"",
            "id":"drill",
            "updateTime":1699510810630,
            "createTime":1699508381436
          }
          this.hasData = false
        }
        this.originData = data
        if (data.name) {
          document.title = data.name
        }
        this.resolve(data)
      }).finally(() => {
        // 加载本地
        this.loadLocal(id)
      })
    },

    // 加载本地
    loadLocal (id) {
      Promise.resolve(storeLocal.getItem(id)).then(res => {
        if (res && res.id) {
          this.isHasLocal = true
          this.resolve(res)
        } else if (this.hasData === false) {
          this.$message({
            type: 'warning',
            message: '未查询到版本内容,未发布版本或页面不存在',
            showClose: true
          })
        }
      })
    },

    // 解析元数据
    resolve (data) {
      // 组件元数据
      let meta = parser.parse(data.meta) || {
        component: 'div',
        name: data.layout || '',
        properts: {},
        layout: {},
        events: {},
        resource: {},
        theme: {},
        childComponents: []
      }
      meta.childComponents = meta.childComponents || []
      data.meta = meta
      this.state = data
      state.page = data
    },

    /**
     * @function 提交
    */
    handleSubmit ({ isShowMessage }) {
      let defer = null
      let state = objecter.clone(this.state)
      // 页面元数据
      state.meta = this.getMetaValue()
      state.meta = parser.stringify(state.meta)
      // 编辑
      defer = Promise.resolve(storeLocal.setItem(this.state.vpid, state))
      return defer.then(() => {
        if (isShowMessage !== false) {
          this.$message({
            message: locale.action.success,
            type: 'success',
            showClose: true
          })
        }
        this.isHasLocal = true
      }).catch(() => {
        this.$message({
          message: locale.action.fail,
          type: 'error',
          showClose: true
        })
      })
    },

    // 使用原始数据
    handleUseOrigin () {
      if (!this.state.id) {
        this.$message({
          message: '无原始数据',
          type: 'warning',
          showClose: true
        })
        return false
      }
      if (this.originData && this.originData.id) {
        this.resolve(this.originData)
      } else {
        this.$message({
          message: '无原始数据',
          type: 'warning',
          showClose: true
        })
      }
    },

    // 清除本地
    handleClearLocal () {
      this.isHasLocal = false
      storeLocal.clear(this.state.vpid)
    },

    // 预览
    handlePreview () {
      window.open(this.getMicroPath('#/saas/preview/' + this.state.vpid))
    },

    /**
     * @function 获取元数据
    */
    getMetaValue () {
      return this.$refs.ddesigner.getMetaValue()
    },

    /**
     * @function 返回
    */
    handleBack () {
      this.$router.push(this.getMicroRoute('/dview/page/list'))
    }
  },

  beforeMount () {
    // 查询所有视图组件
    vcSer.queryAllComponents({ isSaas: true }).then(cps => {
      componentCollection.push(...cps)
      setter.setComponentCollection(componentCollection)
    })
  },

  mounted () {
    let params = this.$route.params
    // 新建
    if (!params.id) {
      params.id = 'tigerlair'
    }
    this.isEdit = true
    this.loadItem(params.id)
  }
}
</script>

<style lang="less" scoped>

</style>

<style lang="less">

</style>
